package myapps.ttclient.asymmetric_encryption;

import java.io.IOException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

public class RSAKeyManager {
	public static int KEY_SIZE = 1024;
	
	private static RSAKeyManager _instance = null;
	
	public static RSAKeyManager getInstance() {
		if(_instance == null) {
			_instance = new RSAKeyManager();
			
			try {
				_instance.intClientKeys();
			} catch(Exception ex) {
				
			}
		}
		
		return _instance;
	}
	
	private RSAKey _clientPublicKey;
	private RSAKey _clientPrivateKey;
	private RSAKey _serverPublicKey;
	
	public RSAKey get_serverPublicKey() {
		return _serverPublicKey;
	}

	public void set_serverPublicKey(RSAKey serverPublicKey) {
		_serverPublicKey = serverPublicKey;
	}

	public RSAKey get_clientPublicKey() {
		return _clientPublicKey;
	}

	public RSAKey get_clientPrivateKey() {
		return _clientPrivateKey;
	}

	private void intClientKeys() throws NoSuchAlgorithmException, 
			InvalidKeySpecException, IOException {
		
		KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
		kpg.initialize(KEY_SIZE);
		
		KeyPair kp = kpg.genKeyPair();

		KeyFactory fact = KeyFactory.getInstance("RSA");
		RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),
				RSAPublicKeySpec.class);
		RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),
				RSAPrivateKeySpec.class);

		_clientPrivateKey = new RSAKey( priv.getModulus(), priv.getPrivateExponent());
		_clientPublicKey = new RSAKey(pub.getModulus(), pub.getPublicExponent());
	}
}
